package con.ess.flutter.channel;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;

public class MainActivity extends FlutterActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initWebViewClient();
    }

    private static final String TAG = "MainActivity";
    private static final int PERMISSION_QUEST_TRTC_CAMERA_VERIFY = 12;
    private static final int PERMISSION_QUEST_CAMERA_RECORD_VERIFY = 11;
    public H5FaceWebChromeClient webViewClient;
    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterEngine
            .getPlatformViewsController()
            .getRegistry()
            .registerViewFactory("plugins.flutter.io/custom_platform_view", new NativeViewFactory(this));
    }

    private void initWebViewClient() {
        Log.d(TAG,"initWebViewClient =====");
        webViewClient = new H5FaceWebChromeClient(MainActivity.this);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult --------"+requestCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11) {//收到录制模式调用系统相机录制完成视频的结果
            Log.d(TAG, "onActivityResult recordVideo");
            if (WBH5FaceVerifySDK.getInstance().receiveH5FaceVerifyResult(requestCode, resultCode, data)) {
                return;
            }
        }else if (requestCode==PERMISSION_QUEST_TRTC_CAMERA_VERIFY){
            Log.d(TAG, "onActivityResult camera");
            requestCameraPermission();
        }else if (requestCode==PERMISSION_QUEST_CAMERA_RECORD_VERIFY){
            Log.d(TAG, "onActivityResult cameraAndSome");
            requestCameraAndSomePermissions(false);
        }


    }

    /**
     * 针对trtc录制模式，申请相机权限
     */
    public void requestCameraPermission() {
        if (checkSdkPermission(Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "checkSelfPermission false");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  //23+的情况
                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CAMERA)) {
                    //用户之前拒绝过，这里返回true
                    Log.d(TAG, "shouldShowRequestPermissionRationale true");
//                showWarningDialog(true);//提醒用户进入设置页面开启权限
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            PERMISSION_QUEST_TRTC_CAMERA_VERIFY);
                } else {
                    Log.d(TAG, "shouldShowRequestPermissionRationale false");
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            PERMISSION_QUEST_TRTC_CAMERA_VERIFY);
                }
            }else {
                //23以下没法系统弹窗动态申请权限，只能用户跳转设置页面，自己打开
                openAppDetail(PERMISSION_QUEST_TRTC_CAMERA_VERIFY);
            }

        } else {
            Log.d(TAG, "checkSelfPermission true");
            webViewClient.enterTrtcFaceVerify();
        }
    }


    private boolean belowApi21;// android 5.0以下系统
    /**
     * 针对老的录制模式，申请相机等其他权限
     */
    public void requestCameraAndSomePermissions(boolean belowApi21) {
        Log.d(TAG,"requestCameraAndSomePermissionsNew");
        this.belowApi21 = belowApi21;
        if (checkSdkPermission(Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED ||
                checkSdkPermission(Manifest.permission.RECORD_AUDIO)!= PackageManager.PERMISSION_GRANTED /*||
                checkSdkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED*/) {
            Log.d(TAG, "checkSelfPermissionNew false");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  //23+的情况
                // 用户之前拒绝过，这个返回true
                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CAMERA) ||
                        ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.RECORD_AUDIO) /*||
                        ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)*/) {
                    //用户同时点选了拒绝开启权限和不再提醒后才会true
                    Log.d(TAG, "shouldShowRequestPermissionRationale true");
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO/*, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE*/},
                            PERMISSION_QUEST_CAMERA_RECORD_VERIFY);
                } else {
                    Log.d(TAG, "shouldShowRequestPermissionRationale false");
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO/*, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE*/},
                            PERMISSION_QUEST_CAMERA_RECORD_VERIFY);
                }
            }else {
                //23以下没法系统弹窗动态申请权限，只能用户跳转设置页面，自己打开
                openAppDetail(PERMISSION_QUEST_CAMERA_RECORD_VERIFY);
            }

        } else {
                webViewClient.enterOldModeFaceVerify(belowApi21);
        }
    }






    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_QUEST_TRTC_CAMERA_VERIFY: // trtc 模式
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "onRequestPermissionsResult grant");
                        webViewClient.enterTrtcFaceVerify();
                    } else if (grantResults[0] == PackageManager.PERMISSION_DENIED
                            && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) == false) {
                        Log.d(TAG, "onRequestPermissionsResult deny");
                        openAppDetail(PERMISSION_QUEST_TRTC_CAMERA_VERIFY);
//                        Toast.makeText(MainActivity.this, "请前往设置->应用->权限中打开相机权限，否则功能无法正常运行", Toast.LENGTH_LONG).show();
//                        权限被拒绝
//                        openAppDetail(PERMISSION_QUEST_TRTC_CAMERA_VERIFY);
                    } else {
                        Log.d(TAG, "拒绝权限并且之前没有点击不再提醒");
                        //权限被拒绝
                        askPermissionError();
                    }
                }
                break;
            case PERMISSION_QUEST_CAMERA_RECORD_VERIFY:
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                            Log.d(TAG,"PERMISSION_QUEST_CAMERA_RECORD_VERIFY GRANTED ");
                                webViewClient.enterOldModeFaceVerify(belowApi21);
                           /* if (grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                                Log.d(TAG, "onRequestPermissionsResult all grant");
                                webViewClient.enterOldModeFaceVerify(belowApi21);
                               *//* if (grantResults[3] == PackageManager.PERMISSION_GRANTED) {
                                    Log.d(TAG, "checkSelfPermission is granted");
                                    webViewClient.enterOldModeFaceVerify(belowApi21);
                                } else {
                                    askPermissionError();
                                }*//*
                            } else {
                                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == false) {
                                    Toast.makeText(MainActivity.this, "请前往设置->应用->权限中打开存储权限，否则功能无法正常运行", Toast.LENGTH_LONG).show();
                                    Log.d(TAG, "onRequestPermissionsResult  sdcard shouldShowRequest false");
                                    //权限被拒绝
                                    openAppDetail(PERMISSION_QUEST_CAMERA_RECORD_VERIFY);
                                } else {
                                    Log.d(TAG, "onRequestPermissionsResult  sdcard deny");
                                    askPermissionError();
                                }
                            }*/
                        } else {
                            if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.RECORD_AUDIO) == false) {
                                Toast.makeText(MainActivity.this, "请前往设置->应用->权限中打开录制权限，否则功能无法正常运行", Toast.LENGTH_LONG).show();
                                //权限被拒绝
                                openAppDetail(PERMISSION_QUEST_CAMERA_RECORD_VERIFY);
                            } else {
                                Log.d(TAG, "onRequestPermissionsResult  record deny");
                                askPermissionError();
                            }
                        }
                    } else {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) == false) {
                            Toast.makeText(MainActivity.this, "请前往设置->应用->权限中打开相机权限，否则功能无法正常运行", Toast.LENGTH_LONG).show();
                            //权限被拒绝
                            openAppDetail(PERMISSION_QUEST_CAMERA_RECORD_VERIFY);
                        } else {
                            Log.d(TAG, "onRequestPermissionsResult  camera deny");
                            askPermissionError();
                        }
                    }
                }

                break;
        }
    }

    private void openAppDetail(int requestCode) {
        showWarningDialog(requestCode);
    }


    private void enterSettingActivity(int requestCode){
        //部分插件化框架中用Activity.getPackageName拿到的不一定是宿主的包名，所以改用applicationContext获取
        String packageName = getApplicationContext().getPackageName();
        Uri uri = Uri.fromParts("package", packageName, null);
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri);
        ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, 0);
        if (resolveInfo != null) {
            startActivityForResult(intent,requestCode);
        }
    }


    private void askPermissionError() {
        Toast.makeText(MainActivity.this, "用户拒绝了权限,退出刷脸", Toast.LENGTH_SHORT).show();
        /*if (mWebView.canGoBack()){
            mWebView.goBack();
        }else {*/
            if (!isFinishing()) {
                finish();
            }
//        }

    }

    //判断是否授权
    private int checkPermission(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // android 23以上
            return this.checkSelfPermission(permission);
        } else {
            return getPackageManager().checkPermission(permission, getPackageName());
        }
    }

    AlertDialog dialog;

    private void showWarningDialog(final int requestCode) {
        dialog = new AlertDialog.Builder(this)
                .setTitle("权限申请提示")
                .setMessage("请前往设置->应用->权限中打开相关权限，否则功能无法正常运行！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        // 一般情况下如果用户不授权的话，功能是无法运行的，做退出处理,合作方自己根据自身产品决定是退出还是停留
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        dialog = null;
                        enterSettingActivity(requestCode);
                        /*if (trtc) {
                            //再次申请权限
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.CAMERA},
                                    PERMISSION_QUEST_TRTC_CAMERA_VERIFY);
                        } else {
                            //再次申请权限
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE*//*, Manifest.permission.READ_PHONE_STATE*//*},
                                    PERMISSION_QUEST_CAMERA_RECORD_VERIFY);
                        }*/

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        dialog = null;
                        /*if (mWebView.canGoBack()){
                            mWebView.goBack();
                        }else {*/
                            if (!isFinishing()) {
                                finish();
                            }
//                        }

                    }
                }).setCancelable(false).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            dialog = null;
        }
    }

    private int checkSdkPermission(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permissionResult=ContextCompat.checkSelfPermission(this,permission);
            Log.d(TAG,"checkSdkPermission >=23 "+permissionResult+" permission="+permission);
            return permissionResult;
        } else {
            int permissionResult=getPackageManager().checkPermission(permission, getPackageName());
            Log.d(TAG,"checkSdkPermission <23 ="+permissionResult+" permission="+permission);
            return permissionResult;
        }
    }
}